package cn.edu.cqu.bysj.services.hibernate;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.cqu.bysj.domains.UserFavorite;
import cn.edu.cqu.bysj.services.UserFavoriteCRUD;

@Service("UserFavoriteCRUDHibernate")
public class UserFavoriteCRUDHibernate implements UserFavoriteCRUD
{
	private HibernateTemplate ht;
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		ht = new HibernateTemplate(sessionFactory);
	}
	
	@Transactional
	@Override
	public String add(UserFavorite userFavorite)
	{
		ht.save(userFavorite);
		return userFavorite.getFavID();
	}

	@Override
	public UserFavorite getByID(String favID)
	{
		return ht.get(UserFavorite.class, favID);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserFavorite> getAll()
	{
		List<UserFavorite> userFavorites = (List<UserFavorite>) ht.find("from UserFavorite");
		return userFavorites;
	}
	
	@Transactional
	@Override
	public void edit(String favID, UserFavorite userFavorite)
	{
		UserFavorite u = getByID(favID);
		u.setContentType(userFavorite.getContentType());
		u.setFavContentID(userFavorite.getFavContentID());
		u.setUserID(userFavorite.getUserID());
		u.setPreview(userFavorite.getPreview());
		ht.update(u);

	}

	@Transactional
	@Override
	public void deleteByID(String favID)
	{
		ht.delete(getByID(favID));	
	}

	@Transactional
	@Override
	public void deleteAll()
	{
		List<UserFavorite> ufs = this.getAll();
		for (UserFavorite userFavorite : ufs)
		{
			deleteByID(userFavorite.getFavID());
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserFavorite> getByUserID(String userID)
	{
		String sql = "from UserFavorite where userID=?";
		List<UserFavorite> favorites = (List<UserFavorite>) ht.find(sql, new Object[]{userID});
		if (favorites.size() == 0)
			return null;
		return favorites;
	}

}
